#!/usr/bin/perl
#Programmer: Rory Carmichael
#Purpose: Turn ldist things into line charts describing alignments in google charts api
#Usage: ldist2json.pl <ldist file> [alignment directory]

#Alignment Format
#position org1 org1_emph org2 org2_emph ... orgN orgN_emph

sub print_json {
	my ($colref, $rowref) = @_;
	my @cols = @$colref;
	my @rows = @$rowref;
	my $retval;
	my @types;

	$retval = "{\n\t\"cols\": [\n";
	foreach $col (@cols) {
		my ($label, $type, $role) = split(/\t/, $col);
		push(@types,$type);
		if(!defined($role)) {
			$retval .= "\t\t{\"id\":\"\",\"label\":\"$label\",\"pattern\":\"\",\"type\":\"$type\"},\n";
		} else {
			$retval .= "\t\t{\"id\":\"\",\"label\":\"$label\",\"pattern\":\"\",\"type\":\"$type\", \"p\":{\"role\":\"$role\"}},\n";
		}

	}
	$retval .= "\t],\n\t\"rows\": [\n";
	foreach my $row (@rows) {
		my @cells;
		my @splitrow = @$row;
		my $i=0;
		foreach my $cell (@$row) {
			if($types[$i] eq "string") {
				$cell = "\"$cell\"";
			}
			push(@cells, "{\"v\":$cell,\"f\":null}");
			$i++;
		}
		$retval .= "\t\t{\"c\":[" . join(",", @cells) . "]},\n";
	}
	$retval .= "\t]\n}\n";
	return $retval;
}

my $path = shift;
my $file = [split(/\//, $path)]->[-1];
my $prefix = [split(/\./, $file)]->[0];
my $aln_dir = ".";
$aln_dir = shift if @_;

open(IF, "$path");
my $line;
while($line = <IF>) {
	if(!($line =~ /^Splicing/ || $line =~ /^\s*$/)) {
		last;
	}
}
if ($line !~ /#/) {
	die("disaster! Malformed file at $path\nline was: $line\n");
}

$line =~ s/#//;
$line =~ s/[>|]//g;
my @headers = split(/\s+/, $line);
my @realheaders = "position\tnumber";
my @realrows;
my %rolehash;
foreach my $head (@headers) {
	push(@realheaders, "$head\tnumber", "null\tboolean\temphasis");
}
$line = <IF>; #Eat the blank line

my %cnthash;
my $rowcnt=0;
while(my $line = <IF>) {
	my @realline;
	push(@realline, $rowcnt);
	chomp $line;
	my @splitline = split(/\s+/, $line);
	if($#splitline != $#headers) {
		die("Row with wrong number of values!\n");
	}
	for(my $i=0;$i<=$#splitline;$i++) {
		$cell = $splitline[$i];
		if ($cell eq "-") {
			push(@realline, "null", "false");
		} else {
			if($cnthash{$i} > 0) {
				if ($cell != 0) {
					die("Saw a rare zone inside a rare zone\n");
				}
				$cnthash{$i}--;
				push(@realline, scalar(@splitline)-$i, "true");
			} elsif($cell > 0) {
				$cnthash{$i} = $cell-1;
				push(@realline, scalar(@splitline)-$i, "true");
			} else {
				push(@realline, scalar(@splitline)-$i, "false");
			}
		}
	}
	push(@realrows, [@realline]);
	$rowcnt++;
}

print &print_json(\@realheaders,\@realrows) . "\n";
